import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { nanoid } from "nanoid";

export const useTodoListStore = defineStore(
  "todoList",
  () => {
    //输入框的值
    const inputValue = ref("");
    // 清空输入框
    function clearInput() {
      inputValue.value = "";
    }
    // 待办事项的列表
    const todos = ref([]);
    // 全选的状态
    const isAllCompleted = ref(false);
    // 已完成任务的数量
    const completedCount = computed(
      () => todos.value.filter(todo => todo.isDone === true).length
    );
    // 总任务数量
    const totalCount = computed(() => todos.value.length);
    // 添加新任务
    function addTodo() {
      if (inputValue.value === "") {
        return;
      }
      todos.value.unshift({
        id: nanoid(),
        todo: inputValue.value,
        isDone: false,
      });
      inputValue.value = "";
    }
    // 删除任务
    function deleteTodo(id) {
      todos.value = todos.value.filter(todo => todo.id !== id);
    }
    // 全选或取消
    function toggleAll() {
      isAllCompleted.value = !isAllCompleted.value;
      todos.value.forEach(todo => {
        todo.isDone = isAllCompleted.value;
      });
    }
    // 清除已完成任务
    function clearCompleted() {
      todos.value = todos.value.filter(todo => todo.isDone === false);
    }

    return {
      inputValue,
      clearInput,
      todos,
      isAllCompleted,
      completedCount,
      totalCount,
      addTodo,
      deleteTodo,
      toggleAll,
      clearCompleted,
    };
  },
  {
    persist: true,
  }
);
